package com.sky.service.impl;


import com.sky.constant.EmailErrorConstant;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserDTO;
import com.sky.entity.User;
import com.sky.exception.EmailErrorException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import com.sky.service.UserService;
import com.sky.vo.UserVO;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private final JwtProperties jwtProperties;

    private final UserMapper userMapper;

    public UserServiceImpl(JwtProperties jwtProperties, UserMapper userMapper) {
        this.jwtProperties = jwtProperties;
        this.userMapper = userMapper;
    }

    @Override
    public UserVO login(UserDTO userDTO) {

        UserVO userVO = new UserVO();

        //根据昵称查询用户
        User user = userMapper.selectByNickname(userDTO.getNickname());

        //判断用户是否存在
        if(user != null){
            //判断邮箱是否正确
            if(!user.getEmail().equals(userDTO.getEmail())){
                //如果不正确，报错
                throw new EmailErrorException(EmailErrorConstant.EMAIL_ERROR);
            }
            userVO.setId(user.getId());
            userVO.setNickname(user.getNickname());
            userVO.setEmail(user.getEmail());
        }else{
            //如果不存在表示第一次登录的用户，存入数据库
            userMapper.insertNewUser(userDTO);
            userVO.setId(userDTO.getId());
            userVO.setNickname(userDTO.getNickname());
            userVO.setEmail(userDTO.getEmail());

        }

        //生成token，打包一起返回给前端
        //登陆controller中生成，返回给客户端
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,userVO.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        userVO.setToken(token);


        return userVO;
    }

    @Override
    public String findUserNickname(Long currentId) {
        return userMapper.findUserNickname(currentId);
    }
}
